import json


class PrintSQL:
    def clean_data(self, row):
        """
        清理数据中的HTML标签和处理NULL值
        """
        for key, value in row.items():
            if isinstance(value, str):
                # 清除 HTML 标签，并替换为 'NULL' 或 None
                if '<span' in value:
                    row[key] = 'NULL' if 'NULL' in value else value
                elif value == 'NULL':
                    row[key] = None  # 你也可以选择 'NULL' 或其他表示空值的符号
        return row

    def print_table(self,headers, data):

        # 计算每列的最大宽度，包括表头和数据
        column_widths = [
            max(len(str(row.get(col, ''))) for row in data) if data else 0 for col in headers
        ]

        # 确保列宽足够大以容纳表头
        column_widths = [
            max(len(header), column_width) for header, column_width in zip(headers, column_widths)
        ]

        # 打印表头
        header_str = " | ".join(f"{header:<{column_widths[i]}}" for i, header in enumerate(headers))
        print(f"+{'-' * (len(header_str) + 3)}+")
        print(f"| {header_str} |")
        print(f"+{'-' * (len(header_str) + 3)}+")

        # 打印每一行数据
        for row in data:
            row = self.clean_data(row)  # 清理数据中的 HTML 标签
            row_str = " | ".join(f"{str(row.get(col, '')):<{column_widths[i]}}" for i, col in enumerate(headers))
            print(f"| {row_str} |")

        print(f"+{'-' * (len(header_str) + 3)}+")


# 测试数据
response_json = {
    'error': 0,
    'data': {
        'head': ['id', 'exam_id', 'group_paper_id', 'level_data_key', 'level_pass_score',
                 'target_course_id', 'target_class_id', 'create_date', 'update_date',
                 'creator', 'updator', 'deleted', 'subject_id'],
        'body': [
            {
                'id': '66', 'exam_id': '114', 'group_paper_id': '1545', 'level_data_key': '8',
                'level_pass_score': '45', 'target_course_id': '<span style="color: #b3b3b3">NULL</span>',
                'target_class_id': '<span style="color: #b3b3b3">NULL</span>',
                'create_date': '<span style="color: #b3b3b3">NULL</span>',
                'update_date': '<span style="color: #b3b3b3">NULL</span>',
                'creator': '<span style="color: #b3b3b3">NULL</span>',
                'updator': '<span style="color: #b3b3b3">NULL</span>',
                'deleted': '0', 'subject_id': '2'
            }
        ],
        'msg': '查询耗时 2 毫秒 , 当前返回 1条数据',
        'ext': False
    }}

if __name__ == "__main__":
    # 创建 PrintSQL 实例并打印表格
    printer = PrintSQL()
    headers = response_json['data']['head']
    data = response_json['data']['body']
    printer.print_table(headers, data)